package com.example.mvvmdemo.taobao

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mvvmdemo.base.LoadState
import com.example.mvvmdemo.bean.MapData
import kotlinx.coroutines.launch
import java.lang.Exception
import java.lang.NullPointerException

/**
 * @author Liyg
 * @description:
 * @date :2020/11/3
 */
class OnSellViewModel : ViewModel(){

    val contentList = MutableLiveData<MutableList<MapData>>()

    //当前的加载的状态
    val loadState = MutableLiveData<LoadState>()

    private val mOnSellRepository by lazy {
        OnSellRepository()
    }

    companion object{
        //默认从第一页开始
        const val DEFAULT_PAGE = 1
    }

    //当前页
    private var mCurrentPage = DEFAULT_PAGE
    //判断当前的状态是否是处于加载更多中
    private var isLoaderMore = false

    /**
     * 加载更多内容
     */
    fun loaderMore(){
        println("loadMore...")
        //去加载更多的内容
        isLoaderMore = true
        loadState.value = LoadState.LOAD_MORE_LOADING
        mCurrentPage++
        this.listContentByPage(mCurrentPage)
    }

    /*
    * 加载首页内容
    * */
    fun loadContent(){
        isLoaderMore = false
        loadState.value = LoadState.LOADING
        this.listContentByPage(mCurrentPage)
    }

    /**
     * 通过页码去加载更多内容
     */
    private fun listContentByPage(page:Int){
        //通过挂起的方式免去了回调
        viewModelScope.launch {
            try {
                val onSellList = mOnSellRepository.getOnSellList(page)
                val oldValue = contentList.value ?: mutableListOf()
                oldValue.addAll(onSellList.tbk_dg_optimus_material_response.result_list.map_data)
                contentList.value = oldValue
                if (onSellList.tbk_dg_optimus_material_response.result_list.map_data.isEmpty()) {
                    loadState.value =
                        if(isLoaderMore) LoadState.LOAD_MORE_EMPTY else LoadState.EMPTY
                }else{
                    loadState.value = LoadState.SUCCESS
                }
            }catch (e:Exception){
                e.printStackTrace()
                mCurrentPage--
                //这个空指针异常有可能是onSellList.tbk_dg_optimus_material_response是null
                //也有可能是onSellList.tbk_dg_optimus_material_response.result_list是null
                //导致出现onSellList.tbk_dg_optimus_material_response.result_list.map_data是个空指针异常
                if(e is NullPointerException){
                    //也就是说没有更多内容的时候，会有一个空指针异常返回来，这个是一个数据返回的特殊情况来的
                    loadState.value = LoadState.LOAD_MORE_EMPTY
                }else{
                    loadState.value =
                        if(isLoaderMore) LoadState.LOAD_MORE_ERROR else LoadState.ERROR
                }
            }
        }
    }




}